package com.shareach.http.sys.rpc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shareach.domain.BaseCityDomain;
import com.shareach.http.sys.parameter.BaseCityParameter;
import com.shareach.service.BaseCityService;
import com.shareach.web.basic.Answer;
import com.shareach.web.basic.Ask;
import com.shareach.web.basic.IAskRPC;
@Service("cityQueryRPC")
public class CityQueryRpc implements IAskRPC {
	@Autowired
	private BaseCityService cityService;

	@Override
	public Answer<?> run(Ask ask, String ip) throws Exception {
		BaseCityParameter p = getParameterMap(ask);
		List<BaseCityParameter> results = new ArrayList<BaseCityParameter>();
		if(StringUtils.isBlank(p.code)){
			List<BaseCityDomain> cities = cityService.findAll();
			for(BaseCityDomain city : cities){
				BaseCityParameter d = new BaseCityParameter();
				d.baidu = city.getBaidu().toString();
				d.code = String.valueOf(city.getCode());
				d.dianping = city.getDianping().toString();
				d.name = city.getName();
				d.py = city.getPy();
				d.tel = city.getTel();
				results.add(d);
			}
		}else{
			BaseCityDomain city = cityService.getById(Long.parseLong(p.code));
			BaseCityParameter d = new BaseCityParameter();
			d.baidu = city.getBaidu().toString();
			d.code =String.valueOf(city.getCode());
			d.dianping = city.getDianping().toString();
			d.name = city.getName();
			d.py = city.getPy();
			d.tel = city.getTel();
			results.add(d);
		}
		Answer<List<BaseCityParameter>> result = getAnswer();
		result.setResult(results);
		return result;
	}

	@Override
	public Answer<List<BaseCityParameter>> getAnswer() {
		return new Answer<List<BaseCityParameter>>();
	}

	@Override
	public BaseCityParameter getParameterMap(Ask ask) {
		BaseCityParameter parameter = new BaseCityParameter();
		HashMap<String,Object> map = ask.getRequest();
		parameter.parseFromMap(map);
		return parameter;
	}

}
